﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DA;
using BL;
using BL.Membership;
using OrderDesk.Controllers;

namespace OrderDesk.Areas.Admin.Controllers
{
    [AuthorizePage(UserPermission.AdminCatDeptManagement)]
    public class DepartmentsController : BaseController
    {
        private DepartmentsRepository rep = new DepartmentsRepository();

        //
        // GET: /Admin/Departments/

        public ViewResult Index()
        {
            var departments = rep.GetEntitySet();
            return View(departments.ToList());
        }

        public ViewResult Details(int id)
        {
            Department department = rep.GetEntity(id);
            // TODO: Insert statistics here
            return View(department);
        }

        [AuthorizePage(UserPermission.SuperAdmin)]
        public ActionResult Edit(int? id)
        {
            Department department = null;
            if (id.HasValue)
                department = rep.GetEntity(id.Value);

            if (this.IsClientsAdmin && !id.HasValue)
            {
                ViewBag.ClientId =
                    new ClientsRepository()
                    .GetEntitySet()
                    .ToList()
                    .Select(x => new SelectListItem() { Text = x.Name, Value = x.ClientId.ToString() });
            }

            return View(department);
        }

        [HttpPost]
        public ActionResult Edit(int? id, Department department)
        {
            if (ModelState.IsValid)
            {
                rep.Save(department);
                return RedirectToAction("Index");
            }

            if (this.IsClientsAdmin && !id.HasValue)
            {
                ViewBag.ClientId =
                    new ClientsRepository()
                    .GetEntitySet()
                    .ToList()
                    .Select(x => new SelectListItem() { Text = x.Name, Value = x.ClientId.ToString() });
            }

            return View(department);
        }

        public ActionResult Delete(int id)
        {
            Department department = rep.GetEntity(id);
            return View(department);
        }

        //
        // POST: /Admin/Departments/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            Department department = rep.GetEntity(id);
            rep.Delete(department);

            return RedirectToAction("Index");
        }
    }
}